import 'package:agora_rtc_engine/rtc_engine.dart';
import 'package:agora_rtc_engine/rtc_remote_view.dart' as RtcRemoteView;
import 'package:star_author/config/base_configuration.dart';
import 'package:star_author/utils/websocket_manage/websocket_handler.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../config/api.dart';
import '../../utils/event.dart';
import '../../utils/rong_im/rong_im.dart';
import 'stream_rtc_controller.dart';

//todo:视频播放的悬浮窗
class OverlayVideo {
  static OverlayEntry? _overlayEntry;

  static OverlayEntry _createOverlayEntry() {
    return OverlayEntry(builder: (context) => VideoDialog());
  }

  static show() {
    _overlayEntry = _createOverlayEntry();
    Overlay.of(Get.context!)!.insert(_overlayEntry!);
  }

  static disPlay() {
    StreamConf.liveId = -1;
    _overlayEntry?.remove();
    _overlayEntry = null;
  }

  //隐藏悬浮框
  static hidden() async {
    if (_overlayEntry != null && (_overlayEntry?.mounted ?? false)) {
      StreamConf.uid = -1;
      StreamConf.token = "";
      WebSocketHandle.unSubscribeLiveChannel();
      if (!StreamConf.isShowVideo) {
        await API.checkIfExists(StreamConf.liveId).then((value) {
          if (value.data['in_studio']) {
            //{in_studio: false}
            API.leave(StreamConf.liveId);
          }
        });
      }
      _overlayEntry?.remove();
      _overlayEntry = null;
    }
  }
}

class VideoDialog extends StatefulWidget {
  @override
  _VideoDialogState createState() => _VideoDialogState();
}

class _VideoDialogState extends State<VideoDialog>
    with TickerProviderStateMixin {
  double _left = 0.0; //按钮在屏幕上的x坐标
  double _top = 100.0; //按钮在屏幕上的y坐标 默认值

  bool isLeft = true; //按钮是否在按钮左侧
  bool isEdge = true; //按钮是否处于边缘
  bool isPress = false; //按钮是否被按下

  AnimationController? _controller;
  Animation? _animation; // 松开后按钮返回屏幕边缘的动画

  double width = 90;

  double height = 160;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _left = Get.width - width;
    _top = Get.height - height - 150; //初始化位置
    Event.on('close_studio', (arg) {
      OverlayVideo.hidden();
    });
  }

  @override
  Widget build(BuildContext context) {
    if (StreamConf.uid == 0) {
      return Container();
    }
    return Positioned(
      left: _left,
      top: _top,
      child: Listener(
        //按下后设isPress为true，绘制选中阴影
        onPointerDown: (details) {
          setState(() {
            isPress = true;
          });
        },
        //按下后设isPress为false，不绘制阴影
        //放下后根据当前x坐标与1/2屏幕宽度比较，判断屏幕在屏幕左侧或右侧，设置返回边缘动画
        //动画结束后设置isLeft的值，根据值绘制左/右边缘按钮
        onPointerUp: (e) async {
          setState(() {
            isPress = false;
          });
          var pixelDetails = MediaQuery.of(context).size; //获取屏幕信息
          if (e.position.dx <= pixelDetails.width / 2) {
            _controller = new AnimationController(
                vsync: this,
                duration: new Duration(milliseconds: 100)); //0.1s动画
            _animation =
                new Tween(begin: e.position.dx, end: 0.0).animate(_controller!)
                  ..addListener(() {
                    setState(() {
                      _left = _animation!.value; //更新x坐标
                    });
                  });
            await _controller?.forward(); //等待动画结束
            _controller?.dispose(); //释放动画资源
            setState(() {
              isLeft = true; //按钮在屏幕左侧
            });
          } else {
            _controller = new AnimationController(
                vsync: this, duration: new Duration(milliseconds: 100)); //0.1动画
            _animation =
                new Tween(begin: e.position.dx, end: pixelDetails.width - width)
                    .animate(_controller!) //返回右侧坐标需要减去自身宽度及50，因坐标以图形左上角为基点
                  ..addListener(() {
                    setState(() {
                      _left = _animation!.value; //动画更新x坐标
                    });
                  });
            await _controller?.forward(); //等待动画结束
            _controller?.dispose(); //释放动画资源
            setState(() {
              isLeft = false; //按钮在屏幕左侧
            });
          }

          setState(() {
            isEdge = true; //按钮返回至边缘
          });
        },
        child: GestureDetector(
          //拖拽更新
          onPanUpdate: (details) {
            var pixelDetails = MediaQuery.of(context).size; //获取屏幕信息
            //拖拽后更新按钮信息，是否处于边缘
            if (_left + details.delta.dx > 0 &&
                _left + details.delta.dx < pixelDetails.width - width) {
              setState(() {
                isEdge = false;
              });
            } else {
              setState(() {
                isEdge = true;
              });
            }
            //拖拽更新坐标
            setState(() {
              _left += details.delta.dx;
              _top += details.delta.dy;
            });
          },
          onTap: () {
            if (StreamConf.channelModel!.gold) {
            } else {}
          },
          child: Container(
            height: height,
            width: width,
            child: Stack(
              children: [
                Visibility(
                  child: RtcRemoteView.SurfaceView(
                    channelId: StreamConf.channelKey,
                    uid: StreamConf.uid,
                    renderMode: VideoRenderMode.Hidden,
                  ),
                  visible: StreamConf.uid != 0,
                ),
                Visibility(
                  child: Positioned(
                    child: InkWell(
                      child: Image.asset(
                        'images/lt_common/clear.png',
                        color: Colors.white,
                        fit: BoxFit.fill,
                        width: 13.w,
                        height: 13.w,
                      ),
                      onTap: () {
                        StreamConf.uid = -1;
                        StreamConf.token = "";
                        RongUtil.quitChatRoom();
                        StreamConf.joined = false;
                        WebSocketHandle.unSubscribeLiveChannel(); //订阅
                        StreamConf.remoteState = VideoRemoteState.Stopped;
                        RongUtil.quitChatRoom();
                        API
                            .checkIfExists(StreamConf.liveId)
                            .then((value) async {
                          if (value.data['in_studio']) {
                            await API.leave(StreamConf.liveId);
                            StreamConf.liveId = -1;
                            StreamConf.channelModel = null;
                          }
                        });
                        StreamConf.isJoinRongCould = true;
                        Get.find<StreamRTCController>().engine.leaveChannel();
                        Get.find<StreamRTCController>().destroy();
                        OverlayVideo.hidden();
                      },
                    ),
                    right: 3,
                    top: 3,
                  ),
                  visible: StreamConf.uid != 0,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    try {
      _controller?.dispose();
    } catch (e) {}
    super.dispose();
  }
}
